<template>
  <div class="address-page">
    <h2 class="title">地址管理</h2>

    <!-- 添加地址 -->
    <el-form :model="newAddress" label-width="90px" class="form" :rules="rules" ref="formRef">
      <el-form-item label="收件人姓名:" prop="receiver_name">
        <el-input v-model="newAddress.receiver_name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="收件人电话:" prop="receiver_phone">
        <el-input v-model="newAddress.receiver_phone" placeholder="请输入电话" />
      </el-form-item>
      <el-form-item label="详细地址:" prop="detail">
        <el-input v-model="newAddress.detail" placeholder="请输入详细地址" />
      </el-form-item>
      <el-form-item label="默认地址:">
        <el-switch v-model="newAddress.is_default" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addAddress">添加地址</el-button>
      </el-form-item>
    </el-form>

    <!-- 地址列表 -->
    <el-divider>已保存地址</el-divider>
    <div v-if="addressList.length === 0" class="empty-tip">
      暂无地址信息，请添加地址
    </div>
    <el-card 
      v-for="item in addressList" 
      :key="item.id" 
      class="card"
      :class="{ 'default-address': item.is_default }"
    >
      <div class="info">
        <p><strong>姓名：</strong>{{ item.receiver_name }}</p>
        <p><strong>电话：</strong>{{ item.receiver_phone }}</p>
        <p><strong>地址：</strong>{{ item.detail }}</p>
        <p v-if="item.is_default" class="default-tag">默认地址</p>
      </div>
      <div class="actions">
        <el-button size="small" @click="startEdit(item)">修改</el-button>
        <el-button 
          size="small" 
          type="danger" 
          @click="removeAddress(item.id)"
          :disabled="item.is_default"
        >
          删除
        </el-button>
        <el-button 
          size="small" 
          type="primary" 
          @click="setDefaultAddress(item.id)"
          v-if="!item.is_default"
        >
          设为默认
        </el-button>
      </div>
    </el-card>

    <!-- 分页 -->
    <el-pagination
      v-if="total > 0"
      class="pagination"
      :current-page.sync="pagination.page"
      :page-size.sync="pagination.page_size"
      :page-sizes="[5, 10, 20, 50]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editVisible" title="修改地址">
      <el-form :model="editData" label-width="90px" :rules="rules" ref="editFormRef">
        <el-form-item label="收件人姓名:" prop="receiver_name">
          <el-input v-model="editData.receiver_name" />
        </el-form-item>
        <el-form-item label="收件人电话:" prop="receiver_phone">
          <el-input v-model="editData.receiver_phone" />
        </el-form-item>
        <el-form-item label="详细地址:" prop="detail">
          <el-input v-model="editData.detail" />
        </el-form-item>
        <el-form-item label="默认地址:">
          <el-switch v-model="editData.is_default" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import apiClient from '@/utils/request'

const router = useRouter()



// 验证规则
const rules = {
  receiver_name: [
    { required: true, message: '请输入收件人姓名', trigger: 'blur' },
    { max: 50, message: '长度不超过50个字符', trigger: 'blur' }
  ],
  receiver_phone: [
    { required: true, message: '请输入收件人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { max: 200, message: '长度不超过200个字符', trigger: 'blur' }
  ]
}

// 表单、新增、编辑等数据
const formRef = ref()
const editFormRef = ref()
const newAddress = ref({ receiver_name: '', receiver_phone: '', detail: '', is_default: false })
const editData = ref({ id: null, receiver_name: '', receiver_phone: '', detail: '', is_default: false })
const editVisible = ref(false)

// 地址列表和分页
const addressList = ref([])
const total = ref(0)
const pagination = ref({ page: 1, page_size: 10 })

// API 请求封装
const getAddressList = async (params) => {
  try {
    const res = await apiClient.get('/api/users/addresses/', { params })
    console.log('getAddressList 响应：', res.data)
    return res.data
  } catch (err) {
    console.error('getAddressList 错误:', err)
    throw err
  }
}

const createAddress = async (data) => {
  try {
    const res = await apiClient.post('/api/users/addresses/', data)
    console.log('createAddress 响应：', res.data)
    return res.data
  } catch (err) {
    throw err
  }
}

// 修改地址
const updateAddress = async (id, data) => {
  try {
    const res = await apiClient.put(`/api/users/addresses/${id}/`, data)
    console.log('updateAddress 响应：', res.data)
    return res.data
  } catch (err) {
    throw err
  }
}

const deleteAddress = async (id) => {
  try {
    await apiClient.delete(`/api/users/addresses/${id}/`)
  } catch (err) {
    throw err
  }
}

// 获取地址列表
const fetchAddressList = async () => {
  try {
    const params = {
      page: pagination.value.page,
      page_size: pagination.value.page_size
    }
    const res = await getAddressList(params)

    //自动识别分页或非分页结构
    if (Array.isArray(res)) {
      addressList.value = res
      total.value = res.length
    } else {
      addressList.value = res.results || []
      total.value = res.count || 0
    }
  } catch (err) {
    if (err.response?.status !== 401) {
      ElMessage.error('获取地址列表失败')
    }
  }
}

// 添加地址
const addAddress = async () => {
  try {
    await formRef.value.validate()
const response = await createAddress(newAddress.value)
ElMessage.success('添加成功')

// 清空表单
newAddress.value = { receiver_name: '', receiver_phone: '', detail: '', is_default: false }
formRef.value.resetFields()

// 手动插入新地址到地址列表顶部
addressList.value.unshift(response)

// 保持总数更新
total.value += 1

// 保证只显示前 page_size 条
addressList.value = addressList.value.slice(0, pagination.value.page_size)
  } catch (err) {
    console.error('添加地址失败:', err)
    if (err.response && err.response.data) {
      const data = err.response.data
      let msg = '添加失败'
      if (typeof data === 'object') {
        msg = Object.entries(data).map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(', ') : v}`).join('; ')
      }
      ElMessage.error(msg)
    } else {
      ElMessage.error('添加失败')
    }
  }
}

// 编辑地址
const startEdit = (item) => {
  editData.value = { ...item }
  editVisible.value = true
}

const confirmEdit = async () => {
  try {
    await editFormRef.value.validate()
    const res = await updateAddress(editData.value.id, editData.value)
    console.log('更新地址响应:', res)
    ElMessage.success('修改成功')
    editVisible.value = false
    await fetchAddressList()
  } catch (err) {
    console.error('更新地址失败:', err)
    if (err.response && err.response.data) {
      const data = err.response.data
      let msg = '修改失败'
      if (typeof data === 'object') {
        msg = Object.entries(data).map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(', ') : v}`).join('; ')
      }
      ElMessage.error(msg)
    } else {
      ElMessage.error('修改失败')
    }
  }
}

// 删除地址
const removeAddress = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该地址吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteAddress(id)
    ElMessage.success('删除成功')
    if (addressList.value.length === 1 && pagination.value.page > 1) {
      pagination.value.page -= 1
    }
    await fetchAddressList()
  } catch (err) {
    if (err !== 'cancel') ElMessage.error('删除失败')
  }
}

// 设为默认地址
const setDefaultAddress = async (id) => {
  try {
    const address = addressList.value.find(item => item.id === id)
    if (!address) {
      ElMessage.error('未找到该地址')
      return
    }

    const updatedData = {
      ...address,
      is_default: true
    }

    await updateAddress(id, updatedData)
    ElMessage.success('设置默认地址成功')
    await fetchAddressList()
  } catch (err) {
    handleApiError(err, '设置默认地址失败')
  }
}

// 分页事件
const handleSizeChange = (val) => {
  pagination.value.page_size = val
  fetchAddressList()
}
const handleCurrentChange = (val) => {
  pagination.value.page = val
  fetchAddressList()
}

// 初始加载
onMounted(() => {
  if (!localStorage.getItem('isLoggedIn')) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  fetchAddressList()
})
</script>

<style scoped>
.address-page {
  width: 100%;
  min-height: 100vh;
  padding: 30px;
  background-color: #f5f7fa;
  box-sizing: border-box;
}
.title {
  font-size: 22px;
  margin-bottom: 20px;
}
.form {
  max-width: 500px;
}
.card {
  margin-bottom: 15px;
  position: relative;
}
.info p {
  margin: 4px 0;
}
.actions {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}
.pagination {
  margin-top: 20px;
  justify-content: center;
}
.default-address {
  border-left: 4px solid #409eff;
}
.default-tag {
  color: #409eff;
  font-weight: bold;
}
.empty-tip {
  text-align: center;
  color: #999;
  padding: 20px;
  font-size: 16px;
}
</style>